package client.engine;

import java.io.BufferedWriter;
import java.util.ArrayList;

import server.Person;
import client.ui.IChatRoomTab;

public class ChatRoom {
	
	private String id;
	private ArrayList<Person> participants;
	private IChatRoomTab window;
	private BufferedWriter conversationLog;
	private ChatEngine engine;
	
	public ChatRoom(ChatEngine engine, String id, ArrayList<Person> participants, 
			IChatRoomTab window, BufferedWriter conversationLog)
	{
		this.engine = engine;
		this.id = id;
		this.participants = participants;
		this.window = window;
		this.conversationLog = conversationLog;
	}
	
	public void receiveMessage(String sender, String message)
	{
		try{
			conversationLog.write(sender + ": " + message);
			conversationLog.newLine();
			conversationLog.flush();
		}catch(Exception e){
			
		}
		window.showMessage(message, sender);
	}
	
	public void addParticipant(Person participant)
	{
		participants.add(participant);
		
		window.updateParticipants(getParticipants());
	}
	
	public void removeParticipant(Person participant)
	{
		for(int i = 0; i < participants.size();){
			if(participants.get(i).getUsername().equals(participant.getUsername())){
				participants.remove(i);
			}else{
				i++;
			}
		}
		
		window.updateParticipants(getParticipants());
	}
	
	public void setTab(IChatRoomTab tab)
	{
		window = tab;
	}

	public String getID(){
		
		return id;
		
	}
	
	public ArrayList<String> getParticipants(){
		
		ArrayList<String> names = new ArrayList<String>();
		
		for(int i = 0; i < participants.size(); i++){
			names.add(participants.get(i).getUsername());
		}
		
		return names;
	}
	
	public void closeConversation(){
		
		try{
			this.conversationLog.close();
		}catch(Exception e){
			
		}
		engine.removeConversation(id);
		
	}
	
	public void inviteBuddy(String name){
		
		engine.inviteBuddyToConversation(id, name);
		
	}
}
